/*
    Copyright 2011 - Tommi Laukkanen (www.substanceofcode.com)

    This file is part of NewsFlow.

    NewsFlow is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    NewsFlow is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with NewsFlow. If not, see <http://www.gnu.org/licenses/>.
*/

import Qt 4.7
import "js/script.js" as Script
import "js/storage.js" as Storage
import "components"

Rectangle {
    id: window
    width: 800
    height: 480
    //anchors.fill: parent
    color: theme.backGroundColor
    z: -666
    property int startIndicator: 0
    property bool isTablet: false //false

    Theme {
        id: theme
    }

    Component.onCompleted: {
        Script.setComponents(navigation, waiting, newsModel, tagsModel, logoContainer, doneIndicator, errorIndicator);
        Storage.getKeyValue("username", setLoginCredentials);
        Storage.getKeyValue("password", setLoginCredentials);
        Storage.getKeyValue("theme", setTheme);
    }

    function setTheme(key, data) {
        if(key=="theme") {
            if(data!=null && data!="" && data.length>0) {
                theme.setTheme(data);
            }
        }
    }

    function setLoginCredentials(key, data) {
        if(key=="username") {
            loginDialog.username = data;
        } else {
            loginDialog.password = data;
        }
        if(loginDialog.username.length>0 &&
                loginDialog.password.length>0) {
            // Auto login
            loginDialog.state = "hidden";
            Script.login(loginDialog.username, loginDialog.password, newsModel);
        } else {
            window.startIndicator++;
            if(window.startIndicator==2) {
                console.log("Try to show login dialog");
                loginDialog.state = "shown";
            }
        }
    }

    ListModel {
        id: newsModel
    }

    ListModel {
        id: tagsModel
    }

    Item {
        id: navigation
        anchors.fill: parent
        state: "hidden"

        MainMenu {
            id: menuList
            width: window.isTablet ? window.width/4 - 20 : window.width
            x: window.isTablet ? 10 : 0
            y: theme.isTablet ? 10 : 0
            height: window.isTablet ? window.height - 10 : window.height

            onClicked: {
                console.log("menu clicked: " + action);
                if(action=="All items") {
                    tagsList.type = 0;
                    Script.loadAllNews();
                } else if(action=="Tags") {
                    tagsList.type = 1;
                    Script.loadTags();
                } else if(action=="Subscriptions") {
                    tagsList.type = 2;
                    Script.loadSubscriptions();
                } else if(action=="Starred items") {
                    tagsList.type = 0;
                    Script.loadStarred();
                } else if(action=="Settings") {
                    navigation.state = "settings";
                } else if(action=="Logout") {
                    navigation.state = "hidden";
                    Storage.setKeyValue("username", "");
                    Storage.setKeyValue("password", "");
                    loginDialog.username = "";
                    loginDialog.password = "";
                    loginDialog.state = "shown";
                    console.log("Login: " + loginDialog.state);
                } else if(action=="Quit") {
                    Qt.quit();
                } else {
                    tagsList.type = 0;
                    tagsModel.clear();
                    Script.loadUnreadNews();
                }
            }
        }

        SettingsMenu {
            id: settingsMenu
            width:  window.isTablet ? window.width / 4 : window.width
            height: window.isTablet ? window.height - 10 : window.height
            x: theme.isTablet ? -settingsMenu.width : window.width
            y: theme.isTablet ? 10 : 0


            onClicked: {
                console.log("Setting: " + action);
                if(action=="Switch theme") {
                    theme.switchTheme();
                    navigation.state = "menu";
                    console.log("BG: " + theme.backGroundColor);
                } else {
                    navigation.state = "menu";
                }
                Storage.setKeyValue("theme", theme.getTheme() + "");
            }

            onBack: {
                navigation.state = "menu";
            }
        }

        TagsList {
            id: tagsList
            width: window.isTablet ? window.width / 4 : window.width
            height: window.isTablet ? window.height - 10 : window.height
            tagsModel: tagsModel
            y: theme.isTablet ? 10 : 0
            x: theme.isTablet ? -tagsList.width : window.width
            property int type: 1

            onClicked: {
                console.log("Loading " + id + " items");
                if(tagsList.type==1) {
                    Script.loadTaggedItems(id);
                } else {
                    Script.loadSubscriptionItems(id);
                }
            }

            onBack: {
                navigation.state = "menu";
            }
        }

        NewsList {
            id: newsList
            width: theme.isTablet ? parent.width/4 - 20 : parent.width
            height: window.isTablet ? window.height - 10 : parent.height
            x: theme.isTablet ? parent.width/4 + 10 : parent.width
            y: theme.isTablet ? 10 : 0
            newsTitlesModel: newsModel

            onClicked: {
                var news = newsModel.get(index);
                if(index==newsModel.count-1 && news.title.indexOf("Load more...")>-1) {
                    newsModel.get(index).title = "Loading...<br/><br/>";
                    Script.loadMore();
                } else {
                    newsPage.index = index;
                    newsPage.model = newsModel;
                    newsPage.title = news.title;
                    if(theme.isTablet) {
                        newsPage.description = news.desc;
                    } else {
                        newsPage.description = "Loading...";
                    }
                    news.isRead = true;
                    newsPage.markAsRead(false);
                    newsPage.source = news.source;
                    newsPage.published = news.published;
                    newsDetails.cachedSummary = news.desc;
                    navigation.state = "detail";
                }
            }

            onBack: {
                if(tagsList.type>0) {
                    navigation.state = "tags";
                } else {
                    navigation.state = "menu";
                }
            }

            onReloadNews: {
                Script.loadNews();
            }
        }

        Rectangle {
            id: newsDetails
            width: theme.isTablet ? parent.width/2 - 20 : parent.width
            height: window.isTablet ? window.height - 10 : parent.height
            //anchors.fill: navigation.state=="fullscreen" ? parent : null
            property string cachedSummary: ""
            color: "#EAFDE6"
            x: theme.isTablet ? parent.width/2 + 10 : parent.width
            y: theme.isTablet ? 10 : 0
            state: "hidden"

            NewsPage {
                id: newsPage
                anchors.fill: parent
                onToggleFullscreen: {
                    if(navigation.state!="fullscreen") {
                        windowHelper.fullscreen();
                        navigation.state = "fullscreen";
                    } else {
                        windowHelper.maximize();
                        navigation.state = "menu";
                    }
                }
                onHide: {
                    navigation.state = "items";
                }
                onMarkAsFavourite: {
                    var news = newsModel.get(index);
                    Script.markAsFavourite(news.id, news.feedUrl);
                }
                onMarkAsRead: {
                    console.log("Marking as read " + index);
                    var news = newsModel.get(index);
                    Script.markAsRead(news.id, news.feedUrl, showWaitingIndicator);
                }
                onMarkAsUnread: {
                    console.log("Marking as unread " + index);
                    var news = newsModel.get(index);
                    Script.markAsUnread(news.id, news.feedUrl);
                }
                onOpenInBrowser: {
                    var news = newsModel.get(index);
                    console.log("Link: " + news.link);
                    Qt.openUrlExternally(news.link);
                }
                onLoadNext: {
                    newsModel.remove( newsModel.count-1 );
                    Script.loadMore();
                }
                onAddTags: {
                    console.log("Tags: " + tags);
                    var news = newsModel.get(index);
                    Script.addTags(news.id, news.feedUrl, tags);
                }
                onShareToFacebook: {
                    var news = newsModel.get(index);
                    var url = "http://www.facebook.com/sharer.php?" +
                        "u=" + news.link +
                        "&t=" + encodeURIComponent(news.title);
                    Qt.openUrlExternally(url);
                }
                onShareToTwitter: {
                    var news = newsModel.get(index);
                    var url = "http://twitter.com/home?" +
                        "status=Reading " + news.link;
                    Qt.openUrlExternally(url);
                }

            }
        }

        // Tablet states
/*
        states: [
            State {
                name: "fullscreen"
                changes: [
                    PropertyChanges { target: newsDetails; width: window.width },
                    PropertyChanges { target: newsDetails; x: 0 },
                    PropertyChanges { target: newsList; visible: false },
                    PropertyChanges { target: menuList; visible: false },
                    PropertyChanges { target: tagsList; visible: false },
                    PropertyChanges { target: settingsMenu; visible: false }
                ]
            },
            State {
                name: "menu"
                changes: [
                    PropertyChanges { target: newsList; visible: true },
                    PropertyChanges { target: menuList; visible: true },
                    PropertyChanges { target: tagsList; visible: true },
                    PropertyChanges { target: settingsMenu; visible: true },
                    PropertyChanges { target: menuList; x: theme.isTablet ? 10 : 0 },
                    PropertyChanges { target: tagsList; x: -tagsList.width },
                    PropertyChanges { target: settingsMenu; x: -tagsList.width },
                    PropertyChanges { target: newsDetails; width: window.width/2 },
                    PropertyChanges { target: newsDetails; x: window.width/2 }
                ]
            },
            State {
                name: "tags"
                changes: [
                    PropertyChanges { target: menuList; x: -menuList.width },
                    PropertyChanges { target: tagsList; x: theme.isTablet ? 10 : 0 },
                    PropertyChanges { target: settingsMenu; x: -settingsMenu.width }
                ]
            },
            State {
                name: "settings"
                changes: [
                    PropertyChanges { target: menuList; x: -menuList.width },
                    PropertyChanges { target: tagsList; x: -tagsList.width },
                    PropertyChanges { target: settingsMenu; x: theme.isTablet ? 10 : 0 }
                ]
            }

        ]*/

        // Mobile states

        states: [
            State {
                name: "hidden"
                changes: [
                    PropertyChanges { target: menuList; x: window.width },
                    PropertyChanges { target: tagsList; x: window.width },
                    PropertyChanges { target: settingsMenu; x: window.width },
                    PropertyChanges { target: newsList; x: window.width },
                    PropertyChanges { target: newsDetails; x: window.width }
                ]
            },
            State {
                name: "menu"
                changes: [
                    PropertyChanges { target: menuList; x: 0 },
                    PropertyChanges { target: tagsList; x: window.width },
                    PropertyChanges { target: settingsMenu; x: window.width },
                    PropertyChanges { target: newsList; x: window.width },
                    PropertyChanges { target: newsDetails; x: window.width }
                ]
            },
            State {
                name: "tags"
                changes: [
                    PropertyChanges { target: menuList; x: -window.width },
                    PropertyChanges { target: tagsList; x: 0 },
                    PropertyChanges { target: settingsMenu; x: window.width },
                    PropertyChanges { target: newsList; x: window.width },
                    PropertyChanges { target: newsDetails; x: window.width }
                ]
            },
            State {
                name: "items"
                changes: [
                    PropertyChanges { target: menuList; x: -window.width },
                    PropertyChanges { target: tagsList; x: -window.width },
                    PropertyChanges { target: settingsMenu; x: window.width },
                    PropertyChanges { target: newsList; x: 0 },
                    PropertyChanges { target: newsDetails; x: window.width }
                ]
            },
            State {
                name: "detail"
                changes: [
                    PropertyChanges { target: menuList; x: -window.width },
                    PropertyChanges { target: tagsList; x: -window.width },
                    PropertyChanges { target: settingsMenu; x: window.width },
                    PropertyChanges { target: newsList; x: -window.width },
                    PropertyChanges { target: newsDetails; x: 0 }
                ]
            },
            State {
                name: "settings"
                changes: [
                    PropertyChanges { target: menuList; x: -menuList.width },
                    PropertyChanges { target: tagsList; x: -menuList.width },
                    PropertyChanges { target: settingsMenu; x: 0 },
                    PropertyChanges { target: newsList; x: -window.width },
                    PropertyChanges { target: newsDetails; x: -window.width }
                ]
            }
        ]

        transitions: [
            Transition {
                ParallelAnimation {
                    NumberAnimation { target: newsList; property: "x"; duration: 500; easing.type: "InOutCubic" }
                    NumberAnimation { target: menuList; property: "x"; duration: 500; easing.type: "InOutCubic" }
                    NumberAnimation { target: settingsMenu; property: "x"; duration: 500; easing.type: "InOutCubic" }
                    NumberAnimation { target: tagsList; property: "x"; duration: 500; easing.type: "InOutCubic" }
                    NumberAnimation { target: newsDetails; property: "x"; duration: 500; easing.type: "InOutCubic" }
                }
            },
            Transition {
                to: "detail"
                SequentialAnimation {
                    ParallelAnimation {
                        NumberAnimation { target: newsList; property: "x"; duration: 500; easing.type: "InOutCubic" }
                        NumberAnimation { target: menuList; property: "x"; duration: 500; easing.type: "InOutCubic" }
                        NumberAnimation { target: settingsMenu; property: "x"; duration: 500; easing.type: "InOutCubic" }
                        NumberAnimation { target: tagsList; property: "x"; duration: 500; easing.type: "InOutCubic" }
                        NumberAnimation { target: newsDetails; property: "x"; duration: 500; easing.type: "InOutCubic" }
                    }
                    ScriptAction {
                        script: {
                            if(theme.isTablet==false) {
                                newsPage.description = newsDetails.cachedSummary;
                                newsPage.markAsRead(false);
                            }
                        }
                    }
                }
            }

        ]
    }

    Rectangle {
        width: parent.width
        height: 4
        color: "#1a1";
    }

    Item {
        id: logoContainer
        y: window.height - height
        width: parent.width
        height: logo.height + copyText.height + 32

        /*Image {
            id: logo
            anchors.horizontalCenter: parent.horizontalCenter
            //anchors.bottom: parent.bottom
            source: "pics/NewsFlow_icon.png"
        }*/

        Text {
            id: logo
            anchors.horizontalCenter: parent.horizontalCenter
            color: "#fff"
            font.pixelSize: 42
            text: "NewsFlow"
        }

        Text {
            id: copyText
            anchors.horizontalCenter: parent.horizontalCenter
            y: logo.height + 16
            color: theme.textColor
            text: "© 2011 Tommi Laukkanen<br/>www.substanceofcode.com"
        }

        states: [
            State {
                name: "hidden"
                PropertyChanges {
                    target: logoContainer
                    y: window.height
                }
            }
        ]

        transitions: Transition {
            SequentialAnimation {
                NumberAnimation { target: logoContainer; property: "y"; duration: 200; easing.type: "InCubic" }
                NumberAnimation { target: newsList; property: "iconOpacity"; duration: 200; to: 0.7 }
            }
        }
    }

    Rectangle {
        id: waiting
        x: 10
        y: 10
        width: parent.width-20
        height: waitIcon.height+20
        color: "#bbb"
        radius: 5
        smooth: true
        state: "hidden"
        opacity: 0.9

        Image {
            y: 10
            id: waitIcon
            source: "pics/sand.png"
        }

        Text {
            id: waitingText
            text: "Please wait..."
            color: "#000"
            font.pixelSize: 22
            anchors.centerIn: parent
        }

        states:
            State {
            name: "hidden"
            PropertyChanges {
                target: waiting
                y: 0 - waiting.height - 1
            }
        }
        State {
            name: "shown"
            PropertyChanges {
                target: waiting
                y: 10
            }
        }

        transitions: Transition {
            SequentialAnimation {
                PropertyAnimation {
                    target: waiting
                    properties: "y"
                    //from:
                    //to: 1
                    duration: 100
                    easing.type: "InCubic"
                }
            }
        }
    }

    Rectangle {
        id: doneIndicator
        anchors.horizontalCenter: parent.horizontalCenter
        y: 10
        width: doneItems.width+30
        height: doneItems.height+20
        property string status: ""
        color: "#bbb"
        radius: 5
        opacity: 0.9
        smooth: true
        state: "hidden"

        Row {
            id: doneItems
            anchors.horizontalCenter: parent.horizontalCenter
            anchors.verticalCenter: parent.verticalCenter
            spacing: 10

            Image {
                source: "pics/accepted_48.png"
            }

            Text {
                id: doneText
                text: "Done! " + doneIndicator.status
                color: "#000"
                font.pixelSize: 22
                anchors.verticalCenter: parent.verticalCenter
            }
        }

        states:
            State {
            name: "hidden"
            PropertyChanges {
                target: doneIndicator
                y: 0 - doneIndicator.height - 1
            }
        }
        State {
            name: "shown"
            PropertyChanges {
                target: doneIndicator
                y: 10
            }
        }

        transitions: Transition {
            SequentialAnimation {
                PropertyAnimation {
                    target: doneIndicator
                    properties: "y"
                    duration: 200
                    easing.type: "InOutCubic"
                }
                PropertyAnimation {
                    target: doneIndicator
                    properties: "y"
                    duration: 2000
                }
                ScriptAction {
                    script: {
                        doneIndicator.state = "hidden";
                    }
                }
            }
        }
    }

    Item {
        id: minimize
        height: 48
        width: 48

        MouseArea {
            anchors.fill: parent
            onClicked: {
                console.log("Minimizing");
                windowHelper.minimize();
            }
        }
    }

    LoginDialog {
        id: loginDialog
        onLogin: {
            Storage.setKeyValue("username", username);
            Storage.setKeyValue("password", password);
            Script.login(username, password, newsModel);
        }
        onExit: {
            Qt.quit();
        }
    }

    ErrorIndicator {
        id: errorIndicator
        width: parent.width
        onShowLogin: {
            loginDialog.state = "shown";
        }
    }
}
